#include "productLoad.h"

int loadProduct(char const * filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	productdata=(struct ProductVars*) calloc(numlines,sizeof(struct ProductVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		sscanf(strtok(buf,"/"), "%d", &productdata[i].id);//get first token from buffer
		strcpy(productdata[i].desc,strtok(NULL,"/"));//subsequent tokens...
		sscanf(strtok(buf,"/"), "%d", &productdata[i].catid);
		sscanf(strtok(buf,"/"), "%d", &productdata[i].agentid);
		sscanf(strtok(buf,"/"), "%d", &productdata[i].stock);
		sscanf(strtok(buf,"/"), "%d", &productdata[i].deliverytime);
		sscanf(strtok(NULL,"/"), "%d", &productdata[i].price);;
	}
	fclose(ptr_file);
	return 0;
}

int writeProducts(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<productcount;i++){
		fprintf(ptr_file,"%d/%s/%d/%d/%d/%d/%d\n",productdata[i].id,productdata[i].desc,productdata[i].catid,productdata[i].agentid,productdata[i].stock,productdata[i].deliverytime,productdata[i].price);
	}
	fclose(ptr_file);
	free(productdata);
	return 0;
}

void addProduct(struct ProductVars n){
	productdata=(struct ProductVars*) realloc(productdata,++productcount*sizeof(struct ProductVars));
	productdata[productcount-1]=n;
}

void rmProduct(int index){
	for(int i=index;i<productcount-1;i++){
		productdata[i]=productdata[i+1];
	}
	productdata=(struct ProductVars*) realloc(productdata,--productcount*sizeof(struct ProductVars));
}